#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using namespace LogModule;

// ./udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    std::string ip = argv[1];
    uint16_t port = (uint16_t)(std::stoi(argv[2]));
    LOG(LogLevel::DEBUG) << "ip: " << ip << " port:" << port;

    // 1.创建socket，（网络类型，UDP）
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error";
        exit(1);
    }
    LOG(LogLevel::INFO) << "socket success, sockfd: " << sockfd;

    // 2.绑定参数，bind，不用显式绑定。
    // 首次发送消息时由OS自动绑定，OS知道IP，端口号由OS随机分配
    struct sockaddr_in peer;
    peer.sin_family = AF_INET;
    peer.sin_port = htons(port);
    peer.sin_addr.s_addr = inet_addr(ip.c_str());

    while (true)
    {
        // 3.客户端发数据
        // 3.1 从标准输入按行读数据
        std::cout << "Please Enter# ";
        std::string data;
        std::getline(std::cin, data);
        // 3.2 发送数据给服务端
        ssize_t ret = sendto(sockfd, data.c_str(), data.size(), 0, (struct sockaddr *)&peer, sizeof(peer));
        (void)ret;

        // 4.接受服务端处理过的数据
        char buff[1024];
        struct sockaddr_in sin;
        socklen_t len = sizeof(struct sockaddr_in);
        ssize_t n = recvfrom(sockfd, buff, 1024, 0, (struct sockaddr *)&sin, &len);

        // 5.使用数据
        buff[n] = 0;
        std::cout << "Server handlered, data: " << buff << std::endl;
    }

    return 0;
}